#!/usr/bin/env ruby
#
# Bundles all files required to build for iOS in a zip archive.
#

require 'open3'
require 'tempfile'

version = ARGV[0] || `git describe --long --tags | cut -f 1 -d "-"`.strip

# First build
puts 'Building...'
_, stderr, status = Open3.capture3('tools/ios-build')
if status != 0
  STDERR.puts stderr
  exit 1
end

# Make archive
puts 'Archiving...'
includes = Dir.glob('include/**/*.h') + Dir.glob('lib/**/*.{h,hpp}')
sources = Dir.glob('swift/Sources/**/*.{swift,h,m}')
libs = Dir.glob('build/ios/*.a')
files = includes + sources + libs
file_name = "TrustWalletCore-iOS-#{version}.zip"
_, stderr, status = Open3.capture3('zip', file_name, *files)
if status != 0
  STDERR.puts stderr
  exit 1
end

# Upload archive
system("aws s3 cp #{file_name} s3://wallet-core/ --acl public-read")

# Upload Cocoapod
puts 'Publishing...'
podspec = <<-PODSPEC
Pod::Spec.new do |s|
  s.name         = 'TrustWalletCore'
  s.version      = '#{version}'
  s.summary      = 'Trust Wallet core data structures and algorithms.'
  s.homepage     = 'https://github.com/TrustWallet/wallet-core'
  s.license      = 'MIT'
  s.authors      = { 'Alejandro Isaza' => 'al@isaza.ca' }

  s.ios.deployment_target = '11.0'
  s.osx.deployment_target = '10.12'
  s.swift_version = '5.1'

  s.source = {
    http: "https://s3.amazonaws.com/wallet-core/TrustWalletCore-iOS-#{version}.zip"
  }
  s.default_subspec = 'Core'

  s.subspec 'Types' do |ss|
    ss.source_files = 
      'swift/Sources/Generated/Enums/*.swift',
      'swift/Sources/Generated/Protobuf/*.swift'
    ss.dependency 'SwiftProtobuf'
  end

  s.subspec 'Core' do |ss|
    ss.preserve_paths = 'build/ios/*.a'
    ss.vendored_libraries =
      'build/ios/libprotobuf.a',
      'build/ios/libTrezorCrypto.a',
      'build/ios/libTrustWalletCore.a'
    s.source_files =
      'include/**/*.h',
      'swift/Sources/*.{swift,h,m,cpp}',
      'swift/Sources/Extensions/*.swift',
      'swift/Sources/Generated/*.{swift,h}'
    ss.public_header_files =
      'include/**/*.h',
      'swift/Sources/*.h'
    ss.libraries = 'c++'
    ss.xcconfig = {
        'SYSTEM_HEADER_SEARCH_PATHS' => '$(inherited) ${PODS_ROOT}/TrustWalletCore/include',
        'OTHER_LDFLAGS' => '$(inherited) -fprofile-instr-generate'
    }
    ss.pod_target_xcconfig = {
        'ARCHS[sdk=iphonesimulator*]' => '$(ARCHS_STANDARD_64_BIT)'
    }
    ss.dependency 'TrustWalletCore/Types'
  end
end
PODSPEC
file = File.new('build/TrustWalletCore.podspec', 'w')
file.write(podspec)
file.close

puts "Done. running 'pod trunk push --allow-warnings #{file.path}'"

system("pod trunk push --allow-warnings #{file.path}")
